import {onBeforeRouteUpdate, useRoute} from "vue-router";
import {getTopCategoryAPI,getCategoryByIdAPI} from "@/apis/category";

export function useCategory() {
    const categoryData = ref([]);
    const route = useRoute();

    const getCategory = async (id) => {
        try {
            console.log('Fetching category with ID:', id); // 调试信息
            const res = await getCategoryByIdAPI(id);
            let updatedCategoryList = Array.isArray(res.data) ? res.data : [];
            categoryData.value = updatedCategoryList;
            console.log('Fetched data:', categoryData.value); // 确认数据已更新
        } catch (error) {
            console.error("Error fetching category:", error);
        }
    };

    // 当组件挂载时获取数据
    onMounted(() => {
        if (route.params.id) {
            getCategory(route.params.id);
        } else {
            console.warn('No category ID provided in the route parameters.');
        }
    });

    // 当路由更新时重新获取数据
    onBeforeRouteUpdate((to) => {
        if (to.params.id) {
            getCategory(to.params.id);
        } else {
            console.warn('No category ID provided in the new route parameters.');
        }
    });

    return {
        categoryData
    };
}